//
//  ViewController.m
//  UseAes
//
//  Created by gitBurning on 14/11/6.
//  Copyright (c) 2014年 gitBurning. All rights reserved.
//

#import "ViewController.h"

#define kKey @"ae125efkk4454eeff444ferfkny6oxi8"
//解码
#import "NSData+Encryption.h"
#import "Base64.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *key = kKey;

    
    /**
     *  加密
     *
     *  @return <#return value description#>
     */
    NSData *data = [@"12345" dataUsingEncoding:NSUTF8StringEncoding];
    NSString *encryptedData = [[data AES256EncryptWithKey:key] base64EncodedStringWithOptions:0];
   
    
    //经过URL编码
    
    NSString *aesStr=[self encodeToPercentEscapeString:encryptedData];
    
    NSLog(@"加密之后%@",aesStr);
    
    /**
     *  解密
     *
     *  @param  <# description#>
     *
     *  @return <#return value description#>
     */
    
    NSString *ciphertexts = aesStr;
    ciphertexts=[self decodeFromPercentEscapeString:ciphertexts];
    
    NSData *cipherData = [NSData dataWithBase64EncodedString:ciphertexts];
    
    NSData *plain = [cipherData AES256DecryptWithKey:key];

    
   NSString * stringValue = [[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding];
    NSLog(@"解密之后%@",stringValue);
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark--url 编码和解码
/**
 *  解码
 *
 *  @param input <#input description#>
 *
 *  @return <#return value description#>
 */
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString *outputStr = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                       (__bridge CFStringRef)input,
                                                                                       NULL,
                                                                                       (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                       kCFStringEncodingUTF8);
    return outputStr;
}
/**
 *  编码
 *
 *  @param input <#input description#>
 *
 *  @return <#return value description#>
 */
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
